﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xna.Framework;
using StreetlightGames.SpaceShooter.Patterns;
using StreetlightGames.XnaEngine;
using System.IO;
using System.Diagnostics;
using StreetlightGames.SpaceShooter.WaveMetaData;

namespace StreetlightGames.SpaceShooter.Toolbox
{
    public partial class WaveDataEditor : Form
    {
        private bool _isLoading;

        private WaveDataCollection _data;
        private WaveData _waveData;
        private ShipGroup _shipGroup;
        private ShipData _shipData;

        private BindingList<WaveData> _list;
        private BindingList<ShipGroup> _groupList;
        private BindingList<PatternData> _patternList;
        private BindingList<ShipData> _shipList;

        public WaveDataEditor()
        {
            InitializeComponent();

            waveDataGridView.AutoGenerateColumns = false;
            groupDataGridView.AutoGenerateColumns = false;
            patternDataGridView.AutoGenerateColumns = false;
            shipDataGridView.AutoGenerateColumns = false;

            List<string> shipTypes = new List<string>();
            shipTypes.Add("BeeShip");
            shipTypes.Add("ButterflyShip");
            shipTypes.Add("MotherShip");
            shipTypeColumn.DataSource = shipTypes;

            List<string> patternTypes = new List<string>();
            patternTypes.Add("Arm Weapons");
            patternTypes.Add("Attack");
            patternTypes.Add("Continue Forward");
            patternTypes.Add("Fly In Circle");
            patternTypes.Add("Hover");
            patternTypes.Add("Move To Formation");
            patternTypes.Add("Move To Target");
            patternTypes.Add("Pattern");
            patternColumn.DataSource = patternTypes;
        }

        public void LoadWaveData(WaveDataCollection data)
        {
            _isLoading = true;

            _list = new BindingList<WaveData>(data);
            _data = data;
            waveDataGridView.DataSource = _list;
            if (data.Count > 0)
            {
                LoadWaveData(data[0]);
            }
            SetWindowTitle();

            _isLoading = false;
        }

        private void LoadWaveData(WaveData waveData)
        {
            if (waveData == null)
            {
                return;
            }
            _waveData = waveData;
            _groupList = new BindingList<ShipGroup>(waveData.Groups);
            groupDataGridView.DataSource = _groupList;
            if (waveData.Groups.Count > 0)
            {
                LoadShipGroup(waveData.Groups[0]);
            }
            else
            {
                LoadShipGroup(null);
            }
        }

        private void LoadShipGroup(ShipGroup shipGroup)
        {
            _shipGroup = shipGroup;

            if (shipGroup == null)
            {
                patternDataGridView.DataSource = null;
                patternDataGridView.Visible = false;
                shipDataGridView.DataSource = null;
                shipDataGridView.Visible = false;
                return;
            }

            _patternList = new BindingList<PatternData>(shipGroup.Patterns);
            patternDataGridView.DataSource = _patternList;
            patternDataGridView.Visible = true;

            _shipList = new BindingList<ShipData>(shipGroup.Ships);
            shipDataGridView.DataSource = _shipList;
            shipDataGridView.Visible = true;
        }

        public static void ShowForWaveData(Form mdiParent, WaveDataCollection data)
        {
            WaveDataEditor window = new WaveDataEditor();
            window.WindowState = FormWindowState.Maximized;
            window.MdiParent = mdiParent;
            window.Show();
            window.LoadWaveData(data);
        }

        internal static void ShowForFile(Form owner, string fileName)
        {
            if (!File.Exists(fileName))
            {
                MessageBox.Show(owner, "File not found.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            try
            {
                WaveDataCollection data = WaveDataCollection.FromFile(fileName);
                WaveDataEditor.ShowForWaveData(owner, data);
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(owner, exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Save()
        {
            if (string.IsNullOrEmpty(_data.FileName))
            {
                SaveAs();
            }
            else
            {
                _data.SaveToFile(_data.FileName);
            }
        }

        private void SaveAs()
        {
            string path = Environment.CurrentDirectory;
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "XML Files (*.xml)|*.xml";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _data.SaveToFile(sfd.FileName);
                    SetWindowTitle();
                }
                catch (System.Exception exp)
                {
                    MessageBox.Show(this, exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            Environment.CurrentDirectory = path;
        }

        public void SetWindowTitle()
        {
            if (_data == null || string.IsNullOrEmpty(_data.FileName))
            {
                Text = "Wave Data";
            }
            else
            {
                FileInfo fi = new FileInfo(_data.FileName);
                Text = string.Format("Wave Data: {0}", fi.Name);
            }
        }

        private void waveDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (!_isLoading)
            {
                LoadWaveData(GetSelectedDataBoundItem<WaveData>(waveDataGridView));
            }
        }

        private void groupDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (!_isLoading)
            {
                LoadShipGroup(GetSelectedDataBoundItem<ShipGroup>(groupDataGridView));
            }
        }

        private void fileSaveAsXmlFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveAs();
        }

        private void waveDuplicateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WaveData waveData = _waveData.Duplicate();
            _list.Add(waveData);
        }

        private void shipDuplicateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _shipData = GetSelectedDataBoundItem<ShipData>(shipDataGridView);
            if (_shipData != null)
            {
                ShipData shipData = _shipData.Duplicate();
                _shipList.Add(shipData);
            }
        }

        private void fileSaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void fileExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void filePlayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save();
            Process.Start(Application.StartupPath + "\\StreetlightGames.SpaceShooter.exe", _data.FileName);
        }

        private static T GetSelectedDataBoundItem<T>(DataGridView dataGridView) where T : class
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                return dataGridView.SelectedRows[0].DataBoundItem as T;
            }
            else if (dataGridView.SelectedCells.Count > 0)
            {
                return dataGridView.Rows[dataGridView.SelectedCells[0].RowIndex].DataBoundItem as T;
            }
            return null;
        }

        private void wavePlayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_waveData != null)
            {
                Process.Start(Application.StartupPath + "\\StreetlightGames.SpaceShooter.exe", string.Format("{0} {1}", _data.FileName, _data.IndexOf(_waveData)));
            }
        }
    }
}
